package com.sky.service.admin.impl;

import com.sky.constant.MessageConstant;
import com.sky.exception.DataException;
import com.sky.mapper.common.OrderDetailMapper;
import com.sky.mapper.common.OrderMapper;
import com.sky.mapper.common.UserMapper;
import com.sky.pojo.Orders;
import com.sky.result.Result;
import com.sky.service.admin.ReportService;
import com.sky.service.admin.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Transactional(readOnly = true)
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 根据指定的日期范围统计每天的营业额数据
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public Result<TurnoverReportVO> turnoverStatistics(LocalDate begin, LocalDate end) {
        //1. 参数的校验
        if(null == begin || null == end || begin.isAfter(end)){
            throw new DataException(MessageConstant.DATA_ERROR);
        }

        //2. 构建一个日期集合存储指定范围的每一天的日期
        String beginTime = begin.toString();
        List<String> dateList = new ArrayList<>();
        while (!begin.isAfter(end)){
            dateList.add(begin.toString());
            begin = begin.plusDays(1);
        }

        List<Double> turnoverList = new ArrayList<>(dateList.size());
        //3. 遍历日期集合 然后查询当前日期的营业额数据  然后判断是否为空 如果为空设置为0

        /**
         * 这种代码属于我们公认的最垃圾的代码之一
         */
        /*for (String date : dateList) {
            Double amount = orderMapper.countAmountByDay(date);
            if(null == amount){
                amount = 0.0;
            }
            turnoverList.add(amount);
        }*/

        Map map = orderMapper.countAmountByDay2(dateList, beginTime, end.toString());
        if(null != map && map.size() > 0){
            for (String date : dateList) {
                Object value = map.get(date);
                turnoverList.add(Double.parseDouble(value.toString()));
            }
        }

        //4. 构建返回结果并返回
        TurnoverReportVO vo = TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ",")) // 11-4,11-5,11-6
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();

        return Result.success(vo);
    }

    /**
     * 用户统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public Result<UserReportVO> userStatistics(LocalDate begin, LocalDate end) {
        //1. 校验参数
        if(null == begin || null == end || begin.isAfter(end)){
            throw new DataException(MessageConstant.DATA_ERROR);
        }

        //2. 构建一个日期集合存储指定范围的每一天的日期
        String beginTime = begin.toString();
        List<String> dateList = new ArrayList<>();
        while(!begin.isAfter(end)){
            dateList.add(begin.toString());
            begin = begin.plusDays(1);
        }

        //3. 查询begin之前的用户的总数
        int totalUser = userMapper.countUserLTBeginTime(beginTime);

        //4. 根据日期分组统计每一天的新增用户数量
        Map<String, Object> map = userMapper.countIncrByDays(beginTime, end, dateList);

        //5. 遍历每日的新增数据 然后求每一天的总数量并封装结果返回
        List<Integer> totalUserList = new ArrayList<>(dateList.size());
        List<Integer> newUserList = new ArrayList<>(dateList.size());

        for (String date : dateList) {
            Object incrUserCount = map.get(date);
            newUserList.add(Integer.parseInt(incrUserCount.toString()));
            totalUser += Integer.parseInt(incrUserCount.toString());
            totalUserList.add(totalUser);
        }

        UserReportVO vo = UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .build();
        return Result.success(vo);
    }

    @Override
    public Result<OrderReportVO> orderStatistics(LocalDate begin, LocalDate end) {
        //1. 校验参数
        if(null == begin || null == end || begin.isAfter(end)){
            throw new DataException(MessageConstant.DATA_ERROR);
        }

        //2. 构建一个日期集合存储指定范围的每一天的日期
        String beginTime = begin.toString();
        List<String> dateList = new ArrayList<>();
        while(!begin.isAfter(end)){
            dateList.add(begin.toString());
            begin = begin.plusDays(1);
        }

        //3. 统计某一个时间为范围内的订单总数量
        Integer totalOrderCount = orderMapper.countNumberByTime(beginTime, end, null);

        //4. 统计某一个时间范围内容的有效订单数量
        Integer validOrderCount = orderMapper.countNumberByTime(beginTime, end, Orders.COMPLETE_ORDER);

        //5. 计算订单完成率
        Double orderCompletionRate = null;
        if(null == totalOrderCount || totalOrderCount == 0){
            orderCompletionRate = 0.0;
        }else {
            orderCompletionRate = validOrderCount * 1.0 / totalOrderCount;
        }

        //6. 根据日期分组查询每日订单总数量
        Map<String,Object> map = orderMapper.countNumberByDay(beginTime, end, dateList, null);

        //7. 根据日期分组统计每日有效订单数量
        Map<String,Object> result = orderMapper.countNumberByDay(beginTime, end, dateList, Orders.COMPLETE_ORDER);

        List<Integer> orderCountList = new ArrayList<>(dateList.size());
        List<Integer> validOrderCountList = new ArrayList<>(dateList.size());
        for (String date : dateList) {
            orderCountList.add(Integer.parseInt(map.get(date).toString()));
            validOrderCountList.add(Integer.parseInt(result.get(date).toString()));
        }

        //8. 结果的封装
        OrderReportVO vo = OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();

        return Result.success(vo);
    }

    /**
     * 统计某一个时间范围内销量前10的商品
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public Result<SalesTop10ReportVO> top10(LocalDate begin, LocalDate end) {
        //1. 校验参数
        if(null == begin || null == end || begin.isAfter(end)){
            throw new DataException(MessageConstant.DATA_ERROR);
        }

        //2. 根据时间统计商品的销售数量
        List<Map<String,Object>> list = orderDetailMapper.top10(begin.toString(), end.toString());

        //3. 解析并封装结果返回
        if(null != list && list.size() > 0){
            List<String> nameList = new ArrayList<>(list.size());
            List<Integer> numberList = new ArrayList<>(list.size());

            for (Map<String, Object> map : list) {
                nameList.add(map.get("name").toString());
                numberList.add(Integer.parseInt(map.get("num").toString()));
            }

            SalesTop10ReportVO vo = SalesTop10ReportVO.builder()
                    .nameList(StringUtils.join(nameList, ","))
                    .numberList(StringUtils.join(numberList, ","))
                    .build();

            return Result.success(vo);

        }
        return Result.success();
    }

    /**
     * 导出最近30天的数据
     *
     * @param response
     */
    @Override
    public void export(HttpServletResponse response) throws IOException {
        //1. 通过io读取excel的模板-使用类加载器来加载文件
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("static/运营数据报表模板.xlsx");

        //2. 在内存中创建excel对象
        XSSFWorkbook excel = new XSSFWorkbook(inputStream);

        //3. 获取当前时间 并获取过去30天的时间
        LocalDate end = LocalDate.now().minusDays(1);
        LocalDate begin = end.minusDays(29);

        //4. 填充时间数据到excl对象中
        XSSFSheet sheet = excel.getSheetAt(0);
        XSSFRow row1 = sheet.getRow(1);
        row1.getCell(1).setCellValue(begin + " 至 " + end);

        //5. 调用工作台的service查询概览数据
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(begin, end);

        //6. 把概览数据填充到excel对象中
        XSSFRow row3 = sheet.getRow(3);
        row3.getCell(2).setCellValue(businessDataVO.getTurnover());
        row3.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
        row3.getCell(6).setCellValue(businessDataVO.getNewUsers());

        XSSFRow row4 = sheet.getRow(4);
        row4.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
        row4.getCell(4).setCellValue(businessDataVO.getUnitPrice());

        //7. 遍历日期 查询每一天的运营数据
        int startIndex = 7;
        int index = 0;
        while(!begin.isAfter(end)){
            System.out.println(index + " ++++++++++");
            businessDataVO = workspaceService.getBusinessData(begin, begin);

            //8. 把每天查询到的数据 填充到excel对象中
            XSSFRow row = sheet.getRow(startIndex + index);
            row.getCell(1).setCellValue(begin.toString());
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(3).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(5).setCellValue(businessDataVO.getUnitPrice());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());

            begin = begin.plusDays(1);
            index ++;
        }

        //9. 把excel文件写入到浏览器中
        ServletOutputStream outputStream = response.getOutputStream();
        excel.write(outputStream);

        //10. 关闭流对象 和excel对象
        outputStream.flush();
        outputStream.close();
        inputStream.close();
        excel.close();
    }
}
